package cn.edu.lzzy.utils;

import cn.edu.lzzy.vm.JSONResult;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

public class FileUtils {
    public static final String UPLOAD_PARAM_URL="urls";
    public static final String UPLOAD_PARAM_MESSAGE="msg";
    public static final String UPLOAD_PARAM_STATUS="status";
//    使用随机生成端文件名将文件上传至指定目录

    /***
     * 将结果打包为JSONObject
     *  file：文件
     *  path：上传的文件夹（路径）
     * @return
     */
    public static JSONObject uploadWithRandomName(MultipartFile file,String path){
JSONObject result=new JSONObject();
try{
    String originName=file.getOriginalFilename();
    String suffix= Objects.requireNonNull(originName).substring(originName.lastIndexOf("."));//获取文件扩展名（后缀）
    String newName= UUID.randomUUID().toString()+suffix;//生成随机文件名+后缀

    File f=new File(path+newName);
    file.transferTo(f);
    result.put(UPLOAD_PARAM_URL,newName);
    result.put(UPLOAD_PARAM_MESSAGE,"文件上传成功！");
    result.put(UPLOAD_PARAM_STATUS,true);

}catch (IOException| JSONException e){
    result.put(UPLOAD_PARAM_URL," ");
    result.put(UPLOAD_PARAM_MESSAGE,"文件上传失败："+e.getMessage());
    result.put(UPLOAD_PARAM_STATUS,false);
    e.printStackTrace();
}
return result;

    }
}
